package com.avfh.netcard.controller;

import com.avfh.netcard.common.BaseController;
import com.avfh.netcard.model.Order;
import com.avfh.netcard.model.User;
import com.avfh.netcard.service.IOrderService;
import com.avfh.netcard.util.WxPayKit;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wuhui
 * @since 2017-06-26
 */
@RestController
@RequestMapping("/api/order")
public class OrderController extends BaseController {
    @Autowired
    IOrderService orderService;

    /**
     * 充值记录
     *
     * @param request
     * @param response
     */
    @PostMapping("/list")
    public void list(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, Object> data) {
        String input = data.get("input").toString();
        if (StringUtils.isEmpty(input)) {
            renderJson(response, "请输入SIM号或者手机号！", "1002");
        }
        EntityWrapper<User> wrapper = new EntityWrapper<>();
        wrapper.where("binary telephone={0}", input)
                .orNew("binary sim={0}", input);
        User user = new User().selectOne(wrapper);
        if (user == null) {
            renderJson(response, "账号未注册！", "1002");
        }
        Page<Order> page = getPage(request);
        page = orderService.queryPage(data, page);
        renderJson(response, page);
    }


    /**
     * 确认下单
     * @param request
     * @param response
     * @param data
     * @return
     */
    @PostMapping("/confirmOrder/")
    public void confirmOrder(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, Object> data) {
        data.put("ip", request.getRemoteAddr());
        Map<String, String> orderMap = orderService.createOrder(data);
        orderMap.put("body", "北京艾为飞鸿科技有限公司-流量充值");
        orderMap.put("openid", (String) request.getSession().getAttribute("openId"));
        Map<String, String> map = WxPayKit.initParamsJsApi(orderMap);
        renderJson(response, map);
    }
}
